package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;

public class RateActivity<handler> extends AppCompatActivity implements Runnable {
    private static final String TAG = "MainActivity";
    EditText rmb;
    TextView result;
    float dollarRate = 0f;
    float euroRate = 0f;
    float wonRate = 0f;
    Handler handler;


    @RequiresApi(api = Build.VERSION_CODES.O)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rmb = findViewById(R.id.input_rmb);
        result = findViewById(R.id.result);

        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollarRate = sharedPreferences.getFloat("dollar_rate", 0.0f);
        euroRate = sharedPreferences.getFloat("euro_rate", 0.0f);
        wonRate = sharedPreferences.getFloat("won_rate", 0.0f);
        String updateStr = sharedPreferences.getString("update_str", "");
        Log.i(TAG, "onCreate:dollar=" + dollarRate);
        Log.i(TAG, "onCreate:updateStr=" + updateStr);
        //获取当前日期
          final LocalDate today =LocalDate.now();
        //比较日期
        if (updateStr.equals(today.toString())) {
            Log.i(TAG, "onCreate:日期相等，不从网络获取数据");
        } else {
            //开启线程
            Thread t = new Thread(this);
            t.start();
        }

        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 7) {
                    String val = (String) msg.obj;
                    Log.i(TAG, "handleMessage:val=" + val);
                    Toast.makeText(RateActivity.this, "数据已更新", Toast.LENGTH_SHORT);
                    //result.setText(val);

                    //保存获取的汇率数据
                    SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putFloat("dollar_rate", dollarRate);
                    editor.putFloat("euro_rate", euroRate);
                    editor.putFloat("won_rate", wonRate);
                    //存入当前日期
                    editor.putString("update_str", today.toString());
                    editor.apply();
                    Log.i(TAG, "handleMessage:日期已更新" + today);
                }
                super.handleMessage(msg);
            }
        };
    }


    public void click(View btn) {
        float r = 0.0f;
        if (btn.getId() == R.id.btn_dollar) {
            r = dollarRate;
        } else if (btn.getId() == R.id.btn_euro) {
            r = euroRate;
        } else {
            r = wonRate;
        }
        String str = rmb.getText().toString();
        if (str != null && str.length() > 0) {
            r = r * Float.parseFloat(str);
            result.setText(String.format("%.2f", r));
        } else {
            //提示用户输入
            Toast.makeText(this, "请输入RMB金额", Toast.LENGTH_SHORT).show();
        }
    }

    public void openConfig(View btn) {
        Log.i(TAG, "openConfig:");
        show();
    }

    public void show() {
        Intent config = new Intent(this, ConfigActivity.class);
        config.putExtra("dollar_key", dollarRate);
        config.putExtra("euro_key", euroRate);
        config.putExtra("won_key", wonRate);

        Log.i(TAG, "openConfig:dollarRate=" + dollarRate);
        Log.i(TAG, "openConfig:euroRate=" + euroRate);
        Log.i(TAG, "openConfig:wonRate=" + wonRate);

        startActivity(config);
        startActivityForResult(config, 1);

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == 2) {
            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("new_dollar", 0.1f);
            euroRate = bundle.getFloat("new_euro", 0.1f);
            wonRate = bundle.getFloat("new_won", 0.1f);

            SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate", dollarRate);
            editor.putFloat("euro_rate", euroRate);
            editor.putFloat("won_rate", wonRate);
            editor.apply();

            Log.i(TAG, "onActivityResult:dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult:euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult:wonrRate=" + wonRate);


        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_setting) {
        }
        return super.onOptionsItemSelected(item);
    }

    public void run() {
        Log.i(TAG, "run:......");
        for (int i = 1; i < 3; i++) {
            Log.i(TAG, "run:i=" + i);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Message msg = handler.obtainMessage(7);
        msg.obj = "Hello from run()";
        handler.sendMessage(msg);
        URL url = null;
        try {
            url = new URL("http://www.cny.com/icbc.htm");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            InputStream in = http.getInputStream();
            String html = inputStream2String(in);
            Log.i(TAG, "run:html=" + html);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try{
            Document doc = Jsoup.connect("http://www.usd.cny.com/bankofchina.htm").get();
            Log.i(TAG, "title:" + doc.title());
            Element table=doc.getElementsByTag("table").first();
            Elements trs = table.getElementsByTag("tr");
            for (Element tr : trs) {
                Elements tds = tr.getElementsByTag("td");
                if (tds.size() > 0) {
                    String str = tds.get(0).text();
                    String val = tds.get(5).text();
                    if ("美元".equals(str)) {
                        dollarRate = 100 / Float.parseFloat(val);
                    } else if ("韩元".equals(str)) {
                        wonRate = 100 / Float.parseFloat(val);
                    } else if ("欧元".equals(str)) {
                        euroRate = 100 / Float.parseFloat(val);
                    }
                    Log.i(TAG, "run:tdl=" + tds.get(0).text() + "=>" + tds.get(5).text());
                }
            }
            Elements ee = doc.select("body>section>div>div>article>table>tbody>trinth-child");
            Log.i(TAG, "run:美元=" + ee.text());

            Element d2 = table.selectFirst("tbody>trinth-child(14)>rinth-child(6)");
            Log.i(TAG, "run:韩元=" + d2.text());
        }
        catch(IOException e){
            e.printStackTrace();
        }

        msg.what=7;
        msg.obj="Hello from run()";
        handler.sendMessage(msg);
    }
    private  String inputStream2String(InputStream inputStream)
            throws IOException{
        final int bufferSize=1024;
        final char[]buffer=new char[bufferSize];
        final StringBuilder out=new StringBuilder();
        Reader in=new InputStreamReader(inputStream,"utf-8");
        for(;;){
            int rsz =in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }

}}